package com.human.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.human.server.entity.AssessmentFills;
import com.human.server.entity.Assessments;
import com.human.server.entity.KpiFillDetails;
import com.human.server.entity.Salary;
import com.human.server.enumration.FillDetailStatus;
import com.human.server.enumration.FillStatus;
import com.human.server.mapper.AssessmentFillsMapper;
import com.human.server.mapper.AssessmentsMapper;
import com.human.server.mapper.KpiFillDetailsMapper;
import com.human.server.mapper.SalaryMapper;
import com.human.server.model.response.KpiFillDetailResponse;
import com.human.server.service.IKpiFillDetailsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * KPI填写详情表 服务实现类
 * </p>
 *
 * @author zooy
 * @since 2025-09-11
 */
@Service
@Slf4j
public class KpiFillDetailsServiceImpl extends ServiceImpl<KpiFillDetailsMapper, KpiFillDetails> implements IKpiFillDetailsService {

    @Autowired
    private AssessmentFillsMapper assessmentFillsMapper;

    @Autowired
    private AssessmentsMapper assessmentsMapper;

    @Autowired
    private SalaryMapper salaryMapper;

    @Autowired
    private ChatClient chatClient;

    public void add(List<KpiFillDetails> kpiFillDetailsList) {

        for (KpiFillDetails kpiFillDetails : kpiFillDetailsList) {
            baseMapper.update(new LambdaUpdateWrapper<KpiFillDetails>()
                    .set(KpiFillDetails::getSelfScore, kpiFillDetails.getSelfScore())
                    .set(KpiFillDetails::getSelfComment, kpiFillDetails.getSelfComment())
                    .set(KpiFillDetails::getStatus, FillDetailStatus.SELF_FILLED.getValue())
                    .eq(KpiFillDetails::getId, kpiFillDetails.getId()));
        }

        // 更新考核填充表
        assessmentFillsMapper.update(new LambdaUpdateWrapper<AssessmentFills>()
                .set(AssessmentFills::getFillStatus, FillStatus.IN_PROGRESS.getValue())
                .set(AssessmentFills::getSubmitTime, LocalDateTime.now())
                .eq(AssessmentFills::getId, kpiFillDetailsList.get(0).getFillId()));

    }

    public void updateManagerScore(KpiFillDetails kpiFillDetails) {
        baseMapper.update(new LambdaUpdateWrapper<KpiFillDetails>()
                .set(KpiFillDetails::getManagerScore, kpiFillDetails.getManagerScore())
                .set(KpiFillDetails::getManagerComment, kpiFillDetails.getManagerComment())
                .set(KpiFillDetails::getStatus, FillDetailStatus.MANAGER_REVIEWED.getValue())
                .eq(KpiFillDetails::getId, kpiFillDetails.getId()));

        // 查询本地
        KpiFillDetails kpiFillDetailsLocal = baseMapper.selectById(kpiFillDetails.getId());

        // 查询关联的列表
        List<KpiFillDetails> kpiFillDetailsList = baseMapper.selectList(new LambdaQueryWrapper<KpiFillDetails>()
                .eq(KpiFillDetails::getFillId, kpiFillDetailsLocal.getFillId()));

        // 判断是否都已经填写完成
        boolean allCompleted = kpiFillDetailsList.stream().allMatch(item -> FillDetailStatus.MANAGER_REVIEWED.getValue().equals(item.getStatus()));

        // 更新考核填充表
        if(allCompleted) {
            // 计算最终得分
            double finalScore = kpiFillDetailsList.stream()
                    .mapToDouble(item -> item.getManagerScore().multiply(BigDecimal.valueOf(item.getKpiWeight())).divide(BigDecimal.valueOf(100)).doubleValue())
                    .sum();
            assessmentFillsMapper.update(new LambdaUpdateWrapper<AssessmentFills>()
                    .set(AssessmentFills::getFillStatus, FillStatus.COMPLETED.getValue())
                    .set(AssessmentFills::getFinalScore, finalScore)
                    .set(AssessmentFills::getSubmitTime, LocalDateTime.now())
                    .eq(AssessmentFills::getId, kpiFillDetailsLocal.getFillId()));
        }
    }

    public void updateFinalScore(KpiFillDetails kpiFillDetails) {

        baseMapper.update(new LambdaUpdateWrapper<KpiFillDetails>()
                .set(KpiFillDetails::getFinalScore, kpiFillDetails.getFinalScore())
                .set(KpiFillDetails::getStatus, FillDetailStatus.COMPLETED.getValue())
                .eq(KpiFillDetails::getId, kpiFillDetails.getId()));

        // 查询本地
        KpiFillDetails kpiFillDetailsLocal = baseMapper.selectById(kpiFillDetails.getId());

        // 查询关联的列表
        List<KpiFillDetails> kpiFillDetailsList = baseMapper.selectList(new LambdaQueryWrapper<KpiFillDetails>()
                .eq(KpiFillDetails::getFillId, kpiFillDetailsLocal.getFillId()));

        // 判断是否都已经填写完成
        boolean allCompleted = kpiFillDetailsList.stream().allMatch(item -> FillDetailStatus.COMPLETED.getValue().equals(item.getStatus()));

        // 更新考核填充表
        if(allCompleted) {
            // 计算最终得分
            double finalScore = kpiFillDetailsList.stream()
                    .mapToDouble(item -> item.getFinalScore().multiply(BigDecimal.valueOf(item.getKpiWeight())).divide(BigDecimal.valueOf(100)).doubleValue())
                    .sum();
            assessmentFillsMapper.update(new LambdaUpdateWrapper<AssessmentFills>()
                    .set(AssessmentFills::getFillStatus, FillStatus.COMPLETED.getValue())
                    .set(AssessmentFills::getFinalScore, finalScore)
                    .set(AssessmentFills::getSubmitTime, LocalDateTime.now())
                    .eq(AssessmentFills::getId, kpiFillDetailsLocal.getFillId()));

            // 获取填充详情
            AssessmentFills assessmentFills = assessmentFillsMapper.selectById(kpiFillDetailsLocal.getFillId());

            // 获取考核方案
            Assessments assessments = assessmentsMapper.selectById(assessmentFills.getAssessmentId());

            // 计算工资
            double salaryRate = finalScore / kpiFillDetailsList.size() * 5;

            // 计算工资
             Salary salary = salaryMapper.selectOne(new LambdaQueryWrapper<Salary>()
                    .eq(Salary::getMonth, assessments.getMonth())
                     .eq(Salary::getEmployeeId, assessmentFills.getEmployeeId())
             );

              if(salary != null) {
                    // 计算工资
                    double salaryAmount = salary.getBaseSalary().doubleValue()  + salary.getPerformanceBonus().doubleValue() * salaryRate;
                    // 更新工资表
                    salaryMapper.update(new LambdaUpdateWrapper<Salary>()
                            .set(Salary::getNetSalary, salaryAmount)
                            .eq(Salary::getId, salary.getId()));
              }

        }
    }

    public String analysis(KpiFillDetails kpiFillDetails) {

        // 查询所有的kpi填写内容
        List<KpiFillDetails> kpiFillDetailsList = baseMapper.selectList(new LambdaQueryWrapper<KpiFillDetails>()
                .eq(KpiFillDetails::getFillId, kpiFillDetails.getFillId()));

        // 拼接kpiName，KpiScore和selfComment
        StringBuilder kpiNameAndSelfComment = new StringBuilder();
        for (KpiFillDetails item : kpiFillDetailsList) {
            kpiNameAndSelfComment.append(item.getKpiName()).append("：").append(item.getSelfScore()).append("分，").append(item.getSelfComment()).append("\n");
        }

        String prompt = "请分析以下KPI填写详情，包括自评分数、自评说明" +
                "并根据这些分析员工表现数据。KPI填写详情：" + kpiNameAndSelfComment;

        log.info("prompt: {}", prompt);
        String response = chatClient.prompt(prompt).call().content();

        // 更新kpi填写详情
        assessmentFillsMapper.update(new LambdaUpdateWrapper<AssessmentFills>()
                .set(AssessmentFills::getAiResult, response)
                .eq(AssessmentFills::getId, kpiFillDetails.getFillId()));

        return response;

    }

    public List<KpiFillDetailResponse> getKpiScore() {

        return this.baseMapper.getKpiScore();
    }
}
